<?php 

include 'db_params.php';
### Inicializa Sesion UC
include_once('CAS-UC/CAS.php');

// Uncomment to enable debugging
phpCAS::setDebug();

// Inicializa librería phpCAS
phpCAS::client(CAS_VERSION_2_0, 'sso.uc.cl', 443, '/cas');
phpCAS::setNoCasServerValidation();
//exije estar Logueado uc
phpCAS::forceAuthentication();


#Una vez logueado guarda una variable de sesion boolean que indica si está logueado o no 
if (isset($_SESSION['username'])) 
{
   $_SESSION['username'] = phpCAS::getUser();//this stores their network user id
}

$username=$_SESSION['username'];

###Para hacer logout.
if (isset($_REQUEST['logout'])) 
{
	$_SESSION['loggedInLocally'] = false;
	unset($_SESSION['username']);
	phpCAS::logout();   
}
?>

<?php
// Include FB SDK
require 'facebook-php-sdk/src/facebook.php';

// Create our Application instance
$facebook = new Facebook(array(
  'appId'  => '171539856240090',
  'secret' => '68c7553a8d08f8d85839a76f427f2092',
  'cookie' => true,
));

$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) 
{
  	try 
	{
    	$uid = $facebook->getUser();
    	$me = $facebook->api('/me');
  	} 
	catch (FacebookApiException $e) 
	{
    	error_log($e);
  	}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Turnos UC</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
                
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.css" type="text/css" />
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" type="text/css" />

<script>
    $(document).ready(function()
	{
         $("#codigo_sigla").autocomplete({  source: "functions/listaSiglas.php" })
	});
         

		$(document).ready(function()
		{
		   $("#codigo_sigla").autocomplete({ close:function(event,ui) 
		{
	 var input = $("#codigo_sigla").val();
	 $.get("functions/nomRamoPorSigla.php",{ 'siglaCurso': input},
	 function(data){
		 
		 if (data != ""){
			 
			 $("p1").text(data);
			 
						}
						else{ $("p1").text("");}
					})
		}
	});
             });
                        
</script>
<script>

	function geoLocate()
	{
		if (typeof(navigator.geolocation) != 'undefined') 
		{
			navigator.geolocation.getCurrentPosition(function(position) 
				{
					//Geo=new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
	
					$.getJSON('functions/AjaxGeoReverse.php', {Lat:position.coords.latitude , Lng:position.coords.longitude }, function(json) 
						{
	 						$('#geoloc').html('<p>'+json['Placemark'][0]['address']+'</p>');
						});
					document.getElementById('lat').value=position.coords.latitude;
					document.getElementById('lng').value=position.coords.longitude;
				});
		}
		else
		{
			alert('Tu navegador no soporta geolocalización, por favor intenta usando Google Chrome o Firefox.')
		}
	}
	
	function Init()
		{
			$('#geoloc').html('<p>Intentando geolocalizar tu ubicación</p>');
			geoLocate();
		}
</script>

    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAdvXAW3x9mWzFu3My7JB1EBRl7lPwFGHthOmeAAsZ97l6ruTJ8xTmhLGTimZefYmJjsPqapDjgjdtIg"
            type="text/javascript"></script>
    <script type="text/javascript">

    function initialize() {
		
		var map = new GMap2(document.getElementById("map_canvas"));
        var customUI = map.getDefaultUI();
        map.setUI(customUI);
        var center = new GLatLng(-33.3340138, -70.566465);
        map.setCenter(center, 13);

        var marker = new GMarker(center, {draggable: true});

        GEvent.addListener(marker, "dragstart", function() {
          map.closeInfoWindow();
		  document.getElementById('lat').value=marker.getPoint().lat();
		  document.getElementById('lng').value=marker.getPoint().lng();
        });

        GEvent.addListener(marker, "dragend", function() {
          marker.openInfoWindowHtml('</br><p style="font-size:18px; text-align:center; vertical-align:middle">¡Vivo Aqui!</p>');
		  document.getElementById('lat').value=marker.getPoint().lat();
		  document.getElementById('lng').value=marker.getPoint().lng();
        });

        map.addOverlay(marker);
		
      if (GBrowserIsCompatible()) {
		  
		  navigator.geolocation.getCurrentPosition(function(position) 
				{
					var map = new GMap2(document.getElementById("map_canvas"));
        var customUI = map.getDefaultUI();
        map.setUI(customUI);
        var center = new GLatLng(position.coords.latitude, position.coords.longitude);
        map.setCenter(center, 15);

        var marker = new GMarker(center, {draggable: true});

        GEvent.addListener(marker, "dragstart", function() {
          map.closeInfoWindow();
		  document.getElementById('lat').value=marker.getPoint().lat();
		  document.getElementById('lng').value=marker.getPoint().lng();
        });

        GEvent.addListener(marker, "dragend", function() {
          marker.openInfoWindowHtml('</br><p style="font-size:18px; text-align:center; vertical-align:middle">¡Vivo Aqui!</p>');
		  document.getElementById('lat').value=marker.getPoint().lat();
		  document.getElementById('lng').value=marker.getPoint().lng();
        });

        map.addOverlay(marker);
				
});
								
      }
	 
	  
	  
    }
    </script>


<link href="css/styles.css" rel="stylesheet" type="text/css" />
<link href="css/registration.css" rel="stylesheet" type="text/css">


</head>
<body onLoad="initialize();">
    <div id="fb-root"></div>
    <script>
          window.fbAsyncInit = function() {
            FB.init({
              appId   : '171539856240090',
			  session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it
              status  : false, // check login status
              cookie  : true, // enable cookies to allow the server to access the session
              xfbml   : true // parse XFBML
            });
    
            // whenever the user logs in, we refresh the page
            FB.Event.subscribe('auth.login', function() {
              window.location="registration.php";
            });
          };
    
          (function() {
            var e = document.createElement('script');
            e.src = document.location.protocol + '//connect.facebook.net/es_ES/all.js';
            e.async = true;
            document.getElementById('fb-root').appendChild(e);
          }());
        </script>
     <script>	 
	 $(document).ready(function() 
	 {
		 $('#add_button').click(function() 
		 {
			 $.get('http://www.turnos.feuc.cl/functions/ajax_query.php',
			 			{
							'sigla': $('#codigo_sigla').val(),
							'seccion': $('#numero_seccion').val()
						}, 
						function(data) 
						{
							//alert(data);
							if (data != "")
							{
								rows = data.split(',');
								for(i in rows)
								{
									valores = rows[i].split('##');
									$('#combobox_modulo_'+valores[0]).val(valores[1]);
								}
							}
							$('#codigo_sigla').val("");
                                                        
							$('#numero_seccion').val("");
						}
					);
			 
		 });
	 });
	 </script>
    <div class="container">
        <div class="sidebar1">
            <!-- end .sidebar1 -->
        </div>
        <div class="content">
            <div id="main-content">
            
                <div class="col-left">
                    <h2 class="heading">Turnos UC</h2>
                    <span class="sub-heading">El lugar para encontrar compañeros para hacer turnos!</span>
                </div>
                <div class="subtitle">Registro</div>
                <div class="facebook_panel">
                	<fb:login-button show-faces="true" width="200" max-rows="1" 
                	perms="email,user_birthday,user_location,user_education_history,user_hometown,user_interests,user_online_presence,user_status" 
                    onlogin="registration.php"  autologoutlink="true"></fb:login-button>
                    <label>Para hacer más expedito el ingreso de datos, denos permisos de facebook.</label>
                </div>
				<div>
					<form id="registration" name="registration" method="POST" action="process.php">
						<table class="personalData_table">
							<tr>
								<td>
									<label name="name_label" for="nombre" class="name_label">Nombre:</label>
									<input type="text" name="nombre" class="name_textBox" <?php if($me)if(isset($me['first_name']))echo " value=\"".$me['first_name']."\"";?>/>
								</td>
								<td>
									<label name="lastname_label" for="apellido" class="lastname_label">Apellido:</label>
									<input type="text" name="apellido" class="lastname_textBox" <?php if($me)if(isset($me['last_name']))echo " value=\"".$me['last_name']."\"";?>/>
								</td>
							</tr>
							<tr>
								<td>
									<label name="auto_label" for="automovil" class="auto_label">Tienes auto:</label>
									<select name="automovil" class="auto_comboBox">
										<option value='true' selected="selected">Si
										<option value='false' >No
									</select>
								</td>
							</tr>
						</table>
                        <br />
                        <br />
						<p style="font-size:18px">¿Donde vives?</p> 
						<p id="geoloc"></p>
						<p> 
							<input type="hidden" name="lat"  id="lat"/>
							<input type="hidden" name="lng"  id="lng"/>
							<input name="Aceptar" type="hidden" id="Aceptar_0"  value="radio" checked="checked" />
							<input type="hidden" name="Aceptar" value="radio" id="Aceptar_1" />
                            
                            <div id="map_canvas" style="width: 700px; height: 400px; text-align:center"></div>
                            
							<input name="direccion" type="hidden" id="direccion" size="70" />
							<br /> 
						</p> 
						
						<div class="horario_panel">
							<label class="horario_label">Por favor agregue su horario ingresando los modulos a los que asiste.</label>
							<div class="modulos_panel">
								<table border="1" class="modulos_table">
									<tr>
										<td> </td>
										<td>L</td>
										<td>M</td>
										<td>W</td>
										<td>J</td>
										<td>V</td>
										<td>S</td>
									</tr>
									<?php
										$nombre_dias = array('L','M','W','J','V','S');
										$num_modulos = array(1,2,3,4,5,6,7,8);
										
										for($i = 0; $i < count($num_modulos); ++$i): 
									?>
										
									<tr>
                                    	<td><?= ($i + 1)?></td>
										<?php for($e = 0; $e < count($nombre_dias); ++$e):?>
											<td>
                                            	<?php
													$query = "SELECT id FROM modulos WHERE dia = '$nombre_dias[$e]' AND numero = $num_modulos[$i]";
													$result = mysql_query($query);
													$row = mysql_fetch_array($result);
												?>
                                                <select name="combobox_modulo_<?=$row['id']?>" id="combobox_modulo_<?=$row['id']?>" class="modulo_comboBox">
                                                	<option value"--" selected="selected">--
                                                    <option value="SJ">SJ
                                                    <option value="LC">LC
                                                    <option value="CC">CC
                                                    <option value="CO">CO
                                                </select>
                                             </td>
                                         <?php endfor;?>
									</tr>
									<?php endfor;?>
								</table>
							</div>
							<div class="sigla_panel">
								<div class="codigo_panel">
                                    <label>Sigla del ramo:</label>
                                    <input id="codigo_sigla" type="text" class="codigo_sigla"/>
                                </div>
                                <p1></p1>
                                <div class="numero_panel">
                                    <label>Número de sección:</label>
                                    <input id="numero_seccion" type="number" class="numero_seccion" />
                                </div>
                                <div class="addbutton_panel">
                                    <input type="button" id="add_button" value="Agregar" />
                                </div>
							</div>
						</div>
						<div class="button_panel">
							<input type="submit" name="registrar" id="registrar" value="Registrar" />
						</div>
					</form>
				</div>
                
                
            </div>
            
        </div>
        <div class="footer">
            <p>Todos los derechos Reservados - Turnos UC</p>
            <!-- end .footer -->
        </div>
        <!-- end .container -->
    </div>
</body>
</html>